


/**
 * This is the definition of every thread of the server, which is assigned to one server-client pair. 
 */

/**

 * @author arpitagarwal
 * Copyright 2012, held by Arpit Agarwal, of University of Illinois at Urbana-Champaign. 
 */

package server;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;

import runner.Message;

public class WorkerRunnable implements Runnable {

	protected Socket clientSocket = null;
	protected String serverText = null;
	DataInputStream dataInputStream = null;
	PrintStream printStream = null;
	int serverPort;
	private String messageReceived;
	
	public synchronized String getMessageReceived() {
		if (this.messageReceived != null) {
			String returnMessage = new String(this.messageReceived); 
			this.messageReceived = null; 
			return returnMessage;
		}
		else {
			return ""; 
		}
	}

	public synchronized void setMessageReceived(String str) {
		if (this.messageReceived == null) {
			this.messageReceived = str; 
		} else {
			this.messageReceived += ";" + str;
//			this.messageReceived = str;
		}
	}

	public WorkerRunnable(Socket clientSocket, String serverText) {
		this.clientSocket = clientSocket;
		this.serverText = serverText;
//		this.previousTimeLeft = System.currentTimeMillis();
//		this.previousTimeRight = System.currentTimeMillis();
	}

	public String getInputMessage() {
		char ch;
		String inputString = "";
		try {
			
			if (dataInputStream.available() > 0) {
				ch = (char) dataInputStream.read();
				if (ch == '#') {
					ch = (char) dataInputStream.read();
					while (ch != -1 && ch != '$') {
						inputString = inputString + ch;
						ch = (char) dataInputStream.read();
					}
				}
				setMessageReceived(inputString);
				return inputString;
			} else {
				inputString = "";
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
//		setMessageReceived(inputString);
		return inputString;
	}

	public String formNewLeftDeadMessage() {
		String returnMessage = "";
		returnMessage = returnMessage + "Left:reconnect_left_dead:" + Message.getMyIP() + "-20000:" + "decideDestination" + ":" + "noKey:noValue:" + System.currentTimeMillis() + ":1:noMessage";
		return returnMessage; 
	}
	
	public void run() {
		try {
			while (true) {
				this.dataInputStream = new DataInputStream(
						clientSocket.getInputStream());
				this.printStream = new PrintStream(
						clientSocket.getOutputStream());

				String inputString = getInputMessage();

				if (inputString.length() < 5) {
					continue;
				}
				long time = System.currentTimeMillis();
				
//				String deadDeclaration = isAnybodyDead(time);
				
//				 MultiThreadedServer.print("Request processed. @Time-" + time
//				 + ", Data is- " + inputString);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}